package com.itheima.canal;

import com.itheima.domain.MoneyLog;
import com.itheima.service.MoneyLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.net.URI;
import java.util.List;

/**
 * @program: cache
 * @description: 这个是cannal将数据变化同步到缓存
 * @author: zhanghz001
 * @create: 2021-05-05 18:10
 **/
@Component
@CanalTable("money_log")
public class ZhzMoneyLogSync implements EntryHandler<MoneyLog> {
    @Autowired
    private MoneyLogService moneyLogService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 插入操作的时候会被动检测到数据变化
     * @param moneyLog
     */
    @Override
    public void insert(MoneyLog moneyLog) {
        //查询最新数据
        List<MoneyLog> logList = moneyLogService.list(moneyLog.getUsername());
        //加入到redis中
        redisTemplate.boundHashOps("UserMoneyLog").put(moneyLog.getUsername(),logList);
        //刷新到nginx中,需要先清除掉这部分的缓存
        try {
            String url="192.168.23.128/purse/mlog/top";
            restTemplate.getForObject(url,String.class);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("暂无缓存");
        }finally {
            //实现了缓存同步解决方案
        }
    }
    
    @Override
    public void update(MoneyLog before, MoneyLog after) {
        
    }
    
    @Override
    public void delete(MoneyLog moneyLog) {
        
    }
}
